package com.example.moblie.poll;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.moblie.Config;
import com.example.moblie.R;
import com.example.moblie.R.id;
import com.example.moblie.R.layout;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class create_poll extends Fragment implements OnClickListener {
	/** Called when the activity is first created. */
	private LocationManager locmgr = null;
	LinearLayout linearLayout;
	int EditTextIndex = 8;
	int count = 0;
	String[] options = new String[8];
	Button addBtn, submitBtn, selectBtn, delBtn;
	EditText title;
	ImageView showImg;
	TextView locInfo;
	double lat, lng;

	private static final int CAMERA_REQUEST = 1888;
	private String selectedImagePath;
	private static final int SELECT_PICTURE = 1;
	Uri imageUri = null;
	String img_str = null;

	View thisView;
	
	@Override
	public View onCreateView(LayoutInflater inflater,
			ViewGroup container, Bundle savedInstanceState) {

		// Inflate the layout for this fragment
		thisView = inflater.inflate(R.layout.create_poll , container, false);
		linearLayout = (LinearLayout) thisView.findViewById(R.id.linear);
		addBtn = (Button) thisView.findViewById(R.id.addBtn);
		submitBtn = (Button) thisView.findViewById(R.id.submitBtn);
		selectBtn = (Button) thisView.findViewById(R.id.selectBtn);
		delBtn = (Button) thisView.findViewById(R.id.delBtn);
		showImg = (ImageView) thisView.findViewById(R.id.showImg);
		locInfo = (TextView) thisView.findViewById(R.id.locInfo);
		showImg.setVisibility(View.GONE);
		delBtn.setVisibility(View.GONE);
		
		addBtn.setOnClickListener(this);
		submitBtn.setOnClickListener(this);
		selectBtn.setOnClickListener(this);
		delBtn.setOnClickListener(this);
		
		this.registerForContextMenu(selectBtn);

		
		title = (EditText) thisView.findViewById(R.id.editTitle);
		createEditText(2);

		locmgr = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
		Location location = locmgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		Location l = null;
		List<String> providers = locmgr.getProviders(true);
	    for (int i=providers.size()-1; i>=0; i--) {
	        l = locmgr.getLastKnownLocation(providers.get(i));
	        if (l != null) break;
	    }
	    if (l != null) {
	    	lat = l.getLatitude();
	    	lng = l.getLongitude();
	    }
	    String latlong = "Lat: " + lat + " Long: "+ lng;
	    locInfo.setText(latlong);
		
		return thisView;

	}

	

	@Override  
	public void onCreate(Bundle savedInstanceState) {  
		super.onCreate(savedInstanceState);  
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
	} 

	@Override  
	public void onActivityCreated(Bundle savedInstanceState) {  
		super.onActivityCreated(savedInstanceState);  
		 

	}  
	
	@Override  
    public void onStart() {  
        super.onStart();  

    }  

	public void createEditText(int c) {

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT);
		params.setMargins(15, 5, 15, 5);
		for (int i = 0; i < c; i++) {
			EditText txt1 = new EditText(this.getActivity());
		    txt1 = (EditText) getLayoutInflater(getArguments()).inflate(R.layout.edittextxml, null);
			
			txt1.setId(count);
			txt1.setHint((count + 1) + ".");
			// txt1.setText(options[i]);
			txt1.setLayoutParams(params);
			
			linearLayout.addView(txt1, EditTextIndex + count);
			count++;
		}
	}
	

	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.addBtn: {
			createEditText(1);
			if (count == 8)
				addBtn.setVisibility(View.GONE);
			break;
		}

		case R.id.submitBtn: {
			int c = 0;
			for (int i = 0; i < count; i++) {
				EditText et = null;
				et = (EditText) linearLayout.getChildAt(EditTextIndex + i);
				if (!et.getText().toString().equals("")) {
					options[c] = et.getText().toString();
					c++;
				}
			}

			if (title.getText().toString().equals("")) {
				Toast.makeText(Config.context, "Title cannot null", Toast.LENGTH_LONG)
						.show();
			} else if (c < 2) {
				Toast.makeText(Config.context, "Need minimun 2 options",
						Toast.LENGTH_LONG).show();
			} else {
				submit();
			}

			break;
		}
		case R.id.selectBtn: {
			getActivity().openContextMenu(selectBtn);
			// setContentView(R.layout.create_poll);
			break;
		}
		case R.id.delBtn: {
			showImg.setVisibility(View.GONE);
			delBtn.setVisibility(View.GONE);
			img_str = null;
			break;
		}
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu contextMenu, View view,
			ContextMenuInfo menuInfo) {
		// Inflate the menu; this adds items to the action bar if it is present.
		super.onCreateContextMenu(contextMenu, view, menuInfo);
		contextMenu.add(0, 0, 0, "Camera");
		contextMenu.add(0, 1, 1, "Album");
		contextMenu.add(0, 2, 2, "Exit");
		// return true;
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case 0:
			Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(cameraIntent, CAMERA_REQUEST);
			break;
		case 1:
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			intent.addCategory(Intent.CATEGORY_OPENABLE);
			startActivityForResult(intent, SELECT_PICTURE);
			break;
		case 2:
			getActivity().closeContextMenu();
			break;
		}
		return true;
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == getActivity().RESULT_OK) {
			if (requestCode == CAMERA_REQUEST) {
				Bitmap photo = (Bitmap) data.getExtras().get("data");
				ByteArrayOutputStream bytes = new ByteArrayOutputStream();
				photo.compress(Bitmap.CompressFormat.JPEG, 70, bytes);
				Random randomGenerator = new Random();
				randomGenerator.nextInt();
				String newimagename = randomGenerator.toString() + ".jpg";
				File f = new File(Environment.getExternalStorageDirectory()
						+ File.separator + newimagename);
				byte[] byte_arr = bytes.toByteArray();
				img_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);
				showImg.setImageBitmap(photo);
				showImg.setVisibility(View.VISIBLE);
				delBtn.setVisibility(View.VISIBLE);
				try {
					f.createNewFile();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// write the bytes in file
				/*
				 * FileOutputStream fo = null; try { fo = new
				 * FileOutputStream(f.getAbsoluteFile()); } catch
				 * (FileNotFoundException e) { // TODO Auto-generated catch
				 * block e.printStackTrace(); } try {
				 * fo.write(bytes.toByteArray()); } catch (IOException e) { //
				 * TODO Auto-generated catch block e.printStackTrace(); }
				 */
				// imageUri=f.getAbsolutePath();
				// this is the url that where you are saved the image
	
			}
			if (requestCode == SELECT_PICTURE) {
				Uri selectedImageUri = data.getData();
				selectedImagePath = getPath(selectedImageUri);
				try {
					FileInputStream fileis = new FileInputStream(
							selectedImagePath);
					BufferedInputStream bufferedstream = new BufferedInputStream(
							fileis);
					byte[] bMapArray = new byte[bufferedstream.available()];
					bufferedstream.read(bMapArray);
					Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0,
							bMapArray.length);
					// this is the image that you are choosen
					ByteArrayOutputStream bytes = new ByteArrayOutputStream();
					bMap.compress(Bitmap.CompressFormat.JPEG, 70, bytes);
					byte[] byte_arr = bytes.toByteArray();
					img_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);
					showImg.setImageBitmap(bMap);
					showImg.setVisibility(View.VISIBLE);
					delBtn.setVisibility(View.VISIBLE);
					if (fileis != null) {
						fileis.close();
					}
					if (bufferedstream != null) {
						bufferedstream.close();
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
	}

	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	public void submit() {

		String reply = "", in = "false";
		try {
			HttpPost httpRequest = new HttpPost(
					"http://myfyp.no-ip.org/cs4295/insertpoll.php");
			List<NameValuePair> list1 = new ArrayList<NameValuePair>();
			list1.add(new BasicNameValuePair("userid", "1"));
			list1.add(new BasicNameValuePair("groupid", ""));
			list1.add(new BasicNameValuePair("title", title.getText()
					.toString()));
			list1.add(new BasicNameValuePair("lat", String.valueOf(lat)));
			list1.add(new BasicNameValuePair("lng", String.valueOf(lng)));
			list1.add(new BasicNameValuePair("image", img_str));
			httpRequest.setEntity(new UrlEncodedFormEntity(list1, HTTP.UTF_8));
			HttpResponse response = new DefaultHttpClient()
					.execute(httpRequest);

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			// retrieve http response and save it as a string
			reply = reader.readLine();

			JSONObject json = new JSONObject(reply);

			in = json.getString("insert");
			Toast.makeText(Config.context, in, Toast.LENGTH_LONG).show();
			submitOption(in);

		} catch (Exception e) {
			Toast.makeText(Config.context, "error " + reply, Toast.LENGTH_LONG).show();
		}
	}

	public void submitOption(String id) {
		for (int i = 0; i < options.length; i++) {
			String reply = "", in = "false";
			if (options[i].equals("")) {
				break;
			}
			try {
				HttpPost httpRequest = new HttpPost(
						"http://myfyp.no-ip.org/cs4295/insertpolloption.php");
				List<NameValuePair> list1 = new ArrayList<NameValuePair>();
				list1.add(new BasicNameValuePair("id", id));
				list1.add(new BasicNameValuePair("oid", String.valueOf(i + 1)));
				list1.add(new BasicNameValuePair("option", options[i]));
				httpRequest.setEntity(new UrlEncodedFormEntity(list1,
						HTTP.UTF_8));
				HttpResponse response = new DefaultHttpClient()
						.execute(httpRequest);

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(response.getEntity().getContent()));
				// retrieve http response and save it as a string
				reply = reader.readLine();

				JSONObject json = new JSONObject(reply);

				in = json.getString("insert");
				Toast.makeText(Config.context, in, Toast.LENGTH_LONG).show();
			} catch (Exception e) {
				Toast.makeText(Config.context, "error " + reply, Toast.LENGTH_LONG)
						.show();
			}

		}
	}

	// Start a location listener
	LocationListener onLocationChange = new LocationListener() {
		public void onLocationChanged(Location loc) {
			// sets and displays the lat/long when a location is provided
			String latlong = "Lat: " + loc.getLatitude() + " Long: "+ loc.getLongitude();
			lat = loc.getLatitude();
			lng = loc.getLongitude();
			locInfo.setText(latlong);
			// Toast.makeText(this,
			// "Disconnected. Please re-connect.",Toast.LENGTH_SHORT).show();
		}

		public void onProviderDisabled(String provider) {
			// required for interface, not used
		}

		public void onProviderEnabled(String provider) {
			// required for interface, not used
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// required for interface, not used
		}
	};

	// pauses listener while app is inactive
	@Override
	public void onPause() {
		super.onPause();
		locmgr.removeUpdates(onLocationChange);
	}

	// reactivates listener when app is resumed
	@Override
	public void onResume() {
		super.onResume();
		locmgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
				10000.0f, onLocationChange);
	}
	
}
